﻿#region Usings

using System;
using System.Threading;
using System.Windows.Threading;

#endregion

namespace Gonte.Commands
{
    public class UserInterfaceAsynchronousCommand<R, P>
        : AsynchronousCommand<R, P>
    {
        public UserInterfaceAsynchronousCommand(
            DispatcherObject dispatcher,
            P parameter,
            Invoker invoker,
            SuccessHandler onSuccess,
            ExceptionHandler onException,
            CleanUpHandler onCleanUp)
            : base(parameter, invoker, onSuccess, onException, onCleanUp)
        {
            dispatcher_ = dispatcher;
        }

        protected override void OnSuccess(R result)
        {
            if (onSuccess_ != null)
            {
                dispatcher_.Dispatcher.Invoke
                (
                    DispatcherPriority.Normal,
                    (SendOrPostCallback)delegate
                    {
                        onSuccess_(result);
                    },
                    null
                );
            }
        }

        protected override void OnException(Exception exception)
        {
            if (onException_ != null)
            {
                dispatcher_.Dispatcher.Invoke
                (
                    DispatcherPriority.Normal,
                    (SendOrPostCallback)delegate
                    {
                        onException_(exception);
                    },
                    null
                );
            }
        }

        protected override void OnCleanUp()
        {
            if (onCleanUp_ != null)
            {
                dispatcher_.Dispatcher.Invoke
                (
                    DispatcherPriority.Normal,
                    (SendOrPostCallback)delegate
                    {
                        onCleanUp_(parameter_);
                    },
                    null
                );
            }
        }

        private DispatcherObject dispatcher_;
    }
}
